package rule

import (
	"reflect"
)

func init() {
	Register(NewRuleRequired())
}

type requiredRule struct{}

func (r *requiredRule) Name() string {
	return "required"
}

func (r *requiredRule) Check(in *RuleInput) (err error) {
	if in.Value == nil {
		return in.Error()
	}
	switch in.Value.(type) {
	case string:
		if str := in.Value.(string); str == "" {
			return in.Error()
		}
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128:
		if in.Value == 0 {
			return in.Error()
		}
	}
	if (in.Kind == reflect.Map || in.Kind == reflect.Slice || in.Kind == reflect.Array) && reflect.ValueOf(in.Value).Len() == 0 {
		return in.Error()
	}
	return
}

func NewRuleRequired() *requiredRule {
	return &requiredRule{}
}
